<?php
namespace  Home\Model;

use Think\Model;

/**
 * 购物车 模型 
 */
class GoodsCartModel extends Model
{
    // 添加购物车
    public function addCart(array $data)
    {
        if (empty($data) || !is_array($data))
        {
            return array();
        }
        $result = $this->field('id,goods_num')->where('user_id = "'.$_SESSION['user_id'].'" and goods_id = "'.$_POST['goods_id'].'" and taocan_name = "'.$_POST['taocan_name'].'"')->find();
        //购物车中无商品，添加一条新信息，购物车中已有信息，则数量 +1
        $id = 0;
        if(empty($result)){
            $_POST['user_id'] = $_SESSION['user_id'];
            $_POST['create_time'] = time();
            $data = $this->create();
            $id   = $this->add($data);
        }else{
            $_POST['user_id'] = $_SESSION['user_id'];
            $_POST['update_time'] = time();
            $_POST['goods_num'] = $result['goods_num'] + $_POST['goods_num'];
            $id = $this->where('id="'.$result['id'].'"')->save($_POST);
        }
        return empty($id) ? false : true;
    }
    /**
     * 获取购物车数量 
     */
    public function getCartCount(array $options)
    {
       $isSuccess =  \Common\Tool\Tool::checkPost($options);
       
       if (!$isSuccess) {
           return false;
       }
       
       $count = $this->where($options)->count();
       
       return $count;
    }
   
    /**
     * 获取最新添加购物车的商品 
     */
    public function getNewCartForGood(array $options, Model $model)
    {
        $isSuccess =  \Common\Tool\Tool::checkPost($options);
         
        if (!$isSuccess || !($model instanceof Model)) {
            return false;
        }
        
        $data =  $this->find($options);
       
        if (!empty($data)) {
           $goods = $model->field('title,pic_url,description')->where('id = "'.$data['goods_id'].'"')->find();
           $data = array_merge((array)$goods, $data);
        }
        return $data;
    }
} 